package com.ruike.alisurface.ui.payPage;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TextView;

import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.ICCardUtils;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.CardCreateOrderByProductBean;
import com.ruike.alisurface.bean.CardCreateOrderBySlotBean;
import com.ruike.alisurface.bean.CardInfoBean;
import com.ruike.alisurface.bean.CardOrderBean;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.CardHttp;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.TimeUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class PayCardActivity extends BaseAty implements ICCardUtils.OnReadCardListener {

    @BindView(R.id.payCard_operationTips_tv)
    TextView operationTipsTv;
    @BindView(R.id.payCard_payInfo_tabLayout)
    TableLayout payInfoTabLayout;
    @BindView(R.id.payCard_cardNumber_tv)
    TextView cardNumberTv;
    @BindView(R.id.payCard_payPrice_tv)
    TextView payPriceTv;
    @BindView(R.id.payCard_yemoney_tv)
    TextView yemoneyTv;
    @BindView(R.id.payCard_payTime_tv)
    TextView payTimeTv;
    @BindView(R.id.payCard_countTime_tv)
    TextView countTimeTv;

    List<CarGoodsBeans> paycarlist;//商品 数据
    double money = 0.0f;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pay_card;
    }

    @Override
    protected void initViews() {
        startCountdownTimer(120, countTimeTv, SelectPayTypeActivity.class);
        initTitleBar(false);
    }

    @Override
    protected void initData() {


        // 计算购物车商品的总金额并展示在界面上
        paycarlist = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        if (paycarlist == null || paycarlist.size() <= 0) {
            return;
        }
        for (CarGoodsBeans carGoodsBean : paycarlist) {
            if (carGoodsBean != null && carGoodsBean.getPrice() > 0) {
                money += carGoodsBean.getPrice();
            }
        }
        payPriceTv.setText(new StringBuffer("¥").append(money));

        showProgressDialog("正在创建订单，请稍后...", false);
        if (ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 1) == 1) {
            L.i("按货道展示下单");
            createOrderBySlot();
        } else {
            L.i("按商品类型展示下单");
            createOrderByProduct();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @OnClick({R.id.payCard_goback_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.payCard_goback_imgv:
                startActivity(SelectPayTypeActivity.class, null);
                finish();
                break;
        }
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        // 串口发送的EventBus消息接收
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (requestUrl.endsWith("Rk_Card_CreateOrder_BySlot") || requestUrl.endsWith("Rk_Card_CreateOrder_ByProduct")) { // 按照货道下单返回 或者 按照商品下单返回

            // 无论按照商品下单还是按照货道下单，返回的对象都是一样的
            CardOrderBean cardOrderBean = GsonUtils.json2Model(requestJsonStr, CardOrderBean.class);

            ShopDetailBean shopDetailBean = new ShopDetailBean(cardOrderBean.getData().getId());
            shopDetailBean.setTotal_fee(cardOrderBean.getData().getTotal_fee());
            shopDetailBean.setPay_fee(cardOrderBean.getData().getPay_fee());
            shopDetailBean.setPromotion_fee(cardOrderBean.getData().getPromotion_fee());
            shopDetailBean.setDiscount_fee(cardOrderBean.getData().getDiscount_fee());

            List<ShopDetailBean.OrderDetailsBean> shopOrderDetailsBeanList = new ArrayList<>();
            shopOrderDetailsBeanList.clear();

            for (CardOrderBean.DataBean.DetailsBean detailsBean : cardOrderBean.getData().getDetails()) {
                ShopDetailBean.OrderDetailsBean shopOrderDetailsBean = new ShopDetailBean.OrderDetailsBean();
                shopOrderDetailsBean.setSlotTypeId(detailsBean.getSlotTypeId()); // 货道类型
                shopOrderDetailsBean.setSlotIndex(detailsBean.getSlotIndex()); // 出货货道编号
                shopOrderDetailsBean.setQuantity(detailsBean.getQuantity()); // 出货数量
                shopOrderDetailsBeanList.add(shopOrderDetailsBean);
            }

            shopDetailBean.setDetailOrderList(shopOrderDetailsBeanList);

            showRightTip("订单创建成功，请放卡");
            startReadCard(); // 开始刷卡

        }
    }

    @Override
    public void onError(String requestUrl, String requestMsg) {
        super.onError(requestUrl, requestMsg);
        showErrorTip(requestMsg);
    }

    /**
     * 按照货道下单
     * <p>
     * mchid	是	string	机器ID
     * card_no	是	string	卡号
     * card_pwd	是	string	卡密码
     * details	是	jsonarray	购物详情
     * details—->slotIndex	是	int	货道
     * details—->quantity	是	int	数量
     */
    public void createOrderBySlot() {
        L.i("paycarlist", paycarlist);
        try {

            Map<String, Integer> map = new HashMap<>();
            for (CarGoodsBeans carGoodsBean : paycarlist) {
                String slotIndex = carGoodsBean.getSlotIndexs();
                if (map.containsKey(slotIndex)) {
                    map.put(slotIndex, map.get(slotIndex) + 1);
                } else {
                    map.put(slotIndex, 1);
                }
            }

            List<CardCreateOrderBySlotBean.DetailsBean> detailsBeanList = new ArrayList<>();
            CardCreateOrderBySlotBean.DetailsBean detailsBean;
            for (String key : map.keySet()) {
                detailsBean = new CardCreateOrderBySlotBean.DetailsBean();
                detailsBean.setQuantity(map.get(key)); // 数量
                detailsBean.setSlotIndex(Integer.parseInt(key)); // 货道号
                detailsBeanList.add(detailsBean);
            }

            CardCreateOrderBySlotBean cardCreateOrderBySlotBean = new CardCreateOrderBySlotBean();
            cardCreateOrderBySlotBean.setMchid(ShareUtils.getInstance().getString(ShareKey.MCH_ID, ""));
//            cardCreateOrderBySlotBean.setCard_no(cardNum);
//            cardCreateOrderBySlotBean.setCard_pwd(cardPwd);
            cardCreateOrderBySlotBean.setDetails(detailsBeanList);
            L.i("按货道创建的订单对象：" + cardCreateOrderBySlotBean);

            MchApiHttp.cardCreateOrderBySlot(cardCreateOrderBySlotBean, this);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 按照商品类型下单
     */
    public void createOrderByProduct() {
        L.i("paycarlist", paycarlist);
        try {

            if (paycarlist == null || paycarlist.size() <= 0) {
                L.e("订单数据异常：" + paycarlist);
                return;
            }

            List<CardCreateOrderByProductBean.DetailsBean> detailsBeanList = new ArrayList<>();
            CardCreateOrderByProductBean.DetailsBean detailsBean;
            for (CarGoodsBeans cardGoodsBean : paycarlist) {
                detailsBean = new CardCreateOrderByProductBean.DetailsBean();
                detailsBean.setProductid(cardGoodsBean.getProductid());
                detailsBean.setQuantity(1);
                List<Integer> slotIndexList = GsonUtils.jsonArray2ModelList(cardGoodsBean.getSlotIndexs(), Integer.class);
                detailsBean.setSlotIndexs(slotIndexList);
                detailsBeanList.add(detailsBean);
            }

            CardCreateOrderByProductBean cardCreateOrderByProductBean = new CardCreateOrderByProductBean();
            cardCreateOrderByProductBean.setMchid(ShareUtils.getInstance().getString(ShareKey.MCH_ID, ""));
//            cardCreateOrderByProductBean.setCard_no(cardNum);
//            cardCreateOrderByProductBean.setCard_pwd(cardPwd);
            cardCreateOrderByProductBean.setDetails(detailsBeanList);
            L.i("按商品创建的订单对象：" + cardCreateOrderByProductBean);

            MchApiHttp.cardCreateOrderByProduct(cardCreateOrderByProductBean, this);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void startReadCard() {
        ICCardUtils.setOnICCardGetPwdListener(this); // 设置读卡监听
        ICCardUtils.readWriteMode(true); // 设置开始读卡
    }

    private void stopReadCard() {
        ICCardUtils.readWriteMode(false); // 设置停止读卡
    }

    @Override
    public void onResultCardNumber(String cardNumber, String errorMsg) {
        if (TextUtils.isEmpty(cardNumber)) {
            showErrorTip(errorMsg);
            return;
        }
        stopReadCard();
        // TODO 获取到卡号之后的操作 此处应该是调用后台接口 上传订单号与卡号
        Bundle bundle = new Bundle();
        bundle.putString("pay_type", "weCard");
//        bundle.putSerializable("orderBeanData", shopDetailBean);
        startActivity(PayShowShopActivity.class, bundle);
        finish();
    }

}
